package ext.tianma.part;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.apache.log4j.Logger;

import com.ptc.windchill.enterprise.part.commands.PartDocServiceCommand;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.tianma.number.util.PartUtil;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.workflow.WorkflowUtil;
import wt.change2.ChangeException2;
import wt.change2.ChangeHelper2;
import wt.change2.Changeable2;
import wt.change2.WTChangeActivity2;
import wt.change2.WTChangeOrder2;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.enterprise.RevisionControlled;
import wt.epm.EPMDocument;
import wt.epm.EPMDocumentMaster;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.lifecycle.LifeCycleState;
import wt.lifecycle.State;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.session.SessionServerHelper;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.VersionControlException;
import wt.vc.VersionControlHelper;
import wt.vc.Versioned;
import wt.vc.config.ConfigHelper;
import wt.vc.views.View;
import wt.vc.views.ViewException;
import wt.vc.views.ViewHelper;
import wt.workflow.engine.WfProcess;

/**
 * 部件流程实现类
 * 
 * @author KWang
 *
 */
public class PartWorkflowUtil {
	private static ArrayList list = new ArrayList();
	private static WTArrayList objectList = new WTArrayList();
	private static List<String> stateList = new ArrayList<String>();
	private static Logger logger = Logger.getLogger(PartWorkflowUtil.class);
	private static final String D_VIEW = "Design";

	private static final String NEW_PRODUCT_MODIFY = "NewProductModify";
	private static final String MASS_PRODUCT_MODIFY = "MassProductionReleaseModify";
	private static final String INWORK = "INWORK";
	private static final String APPROVE_MODIFICATIONS = "APPROVE_MODIFICATIONS";
	private static final String NEW_PRODUCT = "NewProduct";
	private static final String MASS_RELEASE = "MassProductionRelease";
	private static final String APPROVEL = "APPROVAL";

	private static final String RELEASED = "RELEASED";

	// 试产
	private static final String TRIAL_PRODUCTION = "TrialProduction";
	// 小批量
	private static final String CUSTOMER_SAMPLE = "CustomerSample";
	// 风险批量
	private static final String RISK_ORDER = "RiskOrder";
	// 试产修改
	private static final String TRIAL_PRODUCTION_MODIFY = "TrialProductionModify";
	// 小批量修改
	private static final String CUSTOMER_SAMPLE_MODIFY = "CustomerSampleModify";
	// 风险批量修改
	private static final String RISK_ORDER_MODIFY = "RiskOrderModify";

	// 原材料属性（是否已经样品承认）
	private static final String WHETHER_PART_RECOGNIZE = "whetherPartRecognize";

	static {
		// 添加状态“新品修改”，“量产发布修改”，“正在工作”，“待批准”，“量产发布”，“新品”
		stateList.add("NewProductModify");
		stateList.add("MassProductionReleaseModify");
		stateList.add("INWORK");
		stateList.add("APPROVE_MODIFICATIONS");
		stateList.add("MassProductionRelease");
		stateList.add("NewProduct");
		stateList.add("APPROVAL");
		// 添加状态“试产”，“小批量”，“风险批量”，“试产修改”，“小批量修改”，“风险批量修改”
		stateList.add("TrialProduction");
		stateList.add("CustomerSample");
		stateList.add("RiskOrder");
		stateList.add("TrialProductionModify");
		stateList.add("CustomerSampleModify");
		stateList.add("RiskOrderModify");
	}

	/**
	 * 根据条件获取随迁对象
	 * 
	 * @param list
	 * @return
	 * @throws WTException
	 */
	public static WTArrayList getObjects(WTArrayList list) throws WTException {
		logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<list=" + list);
		objectList.clear();
		String state = "";
		for (int i = 0; i < list.size(); i++) {
			Object object = list.get(i);
			if (object instanceof ObjectReference) {
				ObjectReference ref = (ObjectReference) object;
				object = ref.getObject();
			}
			if (object instanceof WTPart) {
				WTPart part = (WTPart) object;
				state = IBAUtil.getSoftType(part).getLogicalIdentifier();
				state = state.substring(state.lastIndexOf(".") + 1);
				if (!state.equals("TwoLevelMaterial")) {
					state = part.getLifeCycleState().toString();
					QueryResult qt = WorkflowUtil.getAssociatedProcesses(part);
					if (state.equals("INWORK") || state.equals("REWORK")) {
						if (state.equals("INWORK")) {
							objectList.add(object);
						} else if (state.equals("REWORK")) {
							int count = 0;
							if (qt.size() > 0 && qt != null) {
								while (qt.hasMoreElements()) {
									Object wf = qt.nextElement();
									if (wf instanceof WfProcess) {
										String se = ((WfProcess) wf).getState().toString();
										if (se.equals("OPEN_RUNNING")) {
											count++;
										}
									}
								}
								if (count == 0) {
									objectList.add(object);
								}
							} else {
								objectList.add(object);
							}
						}
					}
				}
			} else if (object instanceof EPMDocument) {
				EPMDocument epm = (EPMDocument) object;
				state = epm.getLifeCycleState().toString();
				if (("INWORK").equals(state) || ("REWORK").equals(state)) {
					objectList.add(object);
				}
			} else if (object instanceof WTDocument) {
				WTDocument document = (WTDocument) object;
				String internalName = ClientTypedUtility.getTypeIdentifier(document).getTypename();
				if (internalName.contains(".DrawingDoc")) {
					state = document.getLifeCycleState().toString();
					QueryResult qt = WorkflowUtil.getAssociatedProcesses(document);
					if (("INWORK").equals(state) || ("REWORK").equals(state)) {
						if (state.equals("INWORK")) {
							objectList.add(object);
						} else if (state.equals("REWORK")) {
							int count = 0;
							if (qt.size() > 0 && qt != null) {
								while (qt.hasMoreElements()) {
									Object wf = qt.nextElement();
									if (wf instanceof WfProcess) {
										String se = ((WfProcess) wf).getState().toString();
										if (se.equals("OPEN_RUNNING")) {
											count++;
										}
									}
								}
								if (count == 0) {
									objectList.add(object);
								}
							} else {
								objectList.add(object);
							}
						}
					}
				}
			}
		}
		return objectList;
	}

	/**
	 * 零部件中的文档不符合要求抛出异常
	 * 
	 * @param thePart
	 *            PBO
	 * @return
	 * @throws WTException
	 */
	public static ArrayList getAllObject(WTPart thePart) throws WTException {
		list.clear();
		getReviewObjects(thePart);
		getList(thePart);
		for (int i = 0; i < list.size(); i++) {
			Object object = list.get(i);
			if (object instanceof WTPart) {
				WTPart part = (WTPart) object;
				getList(part);
			}
		}
		return list;
	}

	/**
	 * 针对某个零部件获取相关的CAD文档和图档类文档根据条件进行操作
	 * 
	 * @param part
	 *            当前零部件
	 * @param al
	 *            流程中的reviewObjs集合
	 * @throws WTException
	 */
	public static void getList(WTPart part) throws WTException {
		QueryResult qr = PartDocServiceCommand.getAssociatedCADDocuments(part); // 获取零部件的CAD文档
		while (qr.hasMoreElements()) {
			Object epm = qr.nextElement();
			list.add(epm);
		}
		QueryResult qd = PartDocServiceCommand.getAssociatedDescribeDocuments(part); // 获取零部件的说明文档
		while (qd.hasMoreElements()) {
			Object wto = qd.nextElement();
			list.add(wto);
		}
	}

	/**
	 * 针对某个零部件获取流程随签对象列表以及零部件下的所有子件
	 * 
	 * @param thePart
	 *            当前零部件
	 * @param list
	 *            流程中的reviewObjs集合
	 * 
	 * @throws WTException
	 */
	public static void getReviewObjects(WTPart thePart) throws WTException {
		QueryResult subNodes = WTPartHelper.service.getUsesWTParts(thePart, WTPartStandardConfigSpec
				.newWTPartStandardConfigSpec(ViewHelper.service.getView(thePart.getViewName()), null));
		while (subNodes.hasMoreElements()) {
			Persistable aSubNodePair[] = (Persistable[]) subNodes.nextElement();
			WTPart tempPa = null;
			Object wo = null;
			if ((aSubNodePair[1] instanceof WTPartMaster)) {
				tempPa = PartUtil.getLatestPartByPartMaster((WTPartMaster) aSubNodePair[1]);
				wo = tempPa;
				list.add(wo);
			}
			if ((aSubNodePair[1] instanceof WTPart)) {
				tempPa = (WTPart) aSubNodePair[1];
				wo = tempPa;
				list.add(wo);
			}
			getReviewObjects(tempPa);
		}
	}

	/**
	 * 检查随签对象是否检出，如果检查则抛出错误
	 * 
	 * @param reviewObjects
	 *            流程中的集合
	 * @throws WTException
	 */
	public static void checkReviewObjectsForSubmit(WTArrayList reviewObjects) throws WTException {
		if (reviewObjects != null && reviewObjects.size() > 0) {
			for (int i = 0; i < reviewObjects.size(); i++) {
				Persistable p = (Persistable) reviewObjects.getPersistable(i);
				if (p instanceof WTPart) {
					WTPart part = (WTPart) p;
					checkObject(part);
					QueryResult qr = PartDocServiceCommand.getAssociatedCADDocuments(part); // 获取零部件的CAD文档
					while (qr.hasMoreElements()) {
						EPMDocument epm = (EPMDocument) qr.nextElement();
						checkObject(epm);
					}
					QueryResult qd = PartDocServiceCommand.getAssociatedDescribeDocuments(part); // 获取零部件的说明文档
					while (qd.hasMoreElements()) {
						WTDocument wd = (WTDocument) qd.nextElement();
						String softType = IBAUtil.getSoftType(wd).getLogicalIdentifier();
						softType = softType.substring(softType.lastIndexOf(".") + 1);
						if (softType.equals("DrawingDoc")) {
							checkObject(wd);
						}
					}
				}
			}
		}
	}

	/**
	 * 检查对象是否检出
	 * 
	 * @param object
	 *            要检查的对象
	 * @return
	 * @throws WTException
	 */
	public static void checkObject(WTObject object) throws WTException {
		StringWriter errBuf = new StringWriter();
		PrintWriter pw = new PrintWriter(errBuf);
		if (ext.com.workflow.WorkflowUtil.isObjectCheckedOut(object)) { // 判断是否检出
			pw.println(object.getDisplayIdentity() + " 被检出.");
		}
		pw.flush();
		if (errBuf.toString().length() > 0) {
			throw new WTException(errBuf.toString());
		}
	}

	/**
	 * 检查主对象相关证书
	 * 
	 * @param part
	 *            要检查的主对象对象
	 * @throws WTException
	 */
	public static void checkCredentials(WTPart part) throws WTException {
		QueryResult qr = PartDocServiceCommand.getAssociatedDescribeDocuments(part); // 获取零部件的说明文档
		int count = 0;
		logger.info("qr                =" + qr.size());
		while (qr.hasMoreElements()) {
			WTDocument wd = (WTDocument) qr.nextElement();
			String softType = ext.com.iba.IBAUtil.getSoftType(wd).getLogicalIdentifier();
			logger.info("softType                      =" + softType);
			logger.info("count                          =" + count);
			logger.info("boolean                       =" + softType.contains("Acknowledgment"));
			if (softType.contains("Acknowledgment")) {
				count++;
			}
		}
		if (count == 0) {
			throw new WTException(part.getNumber() + "没有相关联的样品承认书!");
		}
	}

	/**
	 * @author xuge_ning 检查主对象是否关联零部件批准报告
	 * @param part
	 *            要检查的主对象对象
	 * @throws WTException
	 */
	public static void checkPartsApproveReport(WTPart part) throws WTException {
		QueryResult qr = PartDocServiceCommand.getAssociatedDescribeDocuments(part); // 获取零部件的说明文档
		int count = 0;
		logger.info("qr                =" + qr.size());
		while (qr.hasMoreElements()) {
			WTDocument wd = (WTDocument) qr.nextElement();
			String softType = ext.com.iba.IBAUtil.getSoftType(wd).getLogicalIdentifier();
			logger.info("softType                      =" + softType);
			logger.info("count                          =" + count);
			logger.info("boolean                       =" + softType.contains("PartsApprovalReport"));
			if (softType.contains("PartsApprovalReport")) {
				count++;
			}
		}
		if (count == 0) {
			throw new WTException(part.getNumber() + "没有相关联的零件批准报告!");
		}
	}

	/**
	 * 遍历集合，根据不同对象设置状态
	 * 
	 * @param list
	 *            要遍历的集合
	 * @param state
	 *            要设置的状态
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 */
	public static void setPartState(WTArrayList list, String state) throws WTPropertyVetoException, WTException {

		System.out.println("PBO已发布,开始设置状态===================>>"+"state:"+state);
		System.out.println("===>>reviewObjs:"+list.toString());
		for (int i = 0; i < list.size(); i++) {
			Object object = list.get(i);
			if (object instanceof ObjectReference) {
				ObjectReference ref = (ObjectReference) object;
				object = ref.getObject();
			}
			if (object instanceof WTPart) {
				WTPart part = (WTPart) object;
				part = CoreUtil.getWTPartByNumberAndView(part.getNumber(), part.getViewName());
				ext.com.workflow.WorkflowUtil.setLifeCycleState(part, state);
			} else if (object instanceof EPMDocument) {
				EPMDocument epm = (EPMDocument) object;
				epm = getLatestEPMDocByMaster((EPMDocumentMaster) epm.getMaster());
				ext.com.workflow.WorkflowUtil.setLifeCycleState(epm, state);
			} else if (object instanceof WTDocument) {
				WTDocument wd = (WTDocument) object;
				wd = getLatestDocByMaster((WTDocumentMaster) wd.getMaster());
				ext.com.workflow.WorkflowUtil.setLifeCycleState(wd, state);
			}
		}
	}

	private static EPMDocument getLatestEPMDocByMaster(EPMDocumentMaster master) throws WTException {
		Iterated iter = null;
		QueryResult qr = VersionControlHelper.service.allVersionsOf(master);
		if (qr.hasMoreElements()) {
			EPMDocument latestVersion = (EPMDocument) qr.nextElement();
			iter = VersionControlHelper.service.getLatestIteration(latestVersion, false);
		}

		return (EPMDocument) iter;
	}

	private static WTDocument getLatestDocByMaster(WTDocumentMaster master) throws WTException {
		Iterated iter = null;
		QueryResult qr = VersionControlHelper.service.allVersionsOf(master);
		if (qr.hasMoreElements()) {
			WTDocument latestVersion = (WTDocument) qr.nextElement();
			iter = VersionControlHelper.service.getLatestIteration(latestVersion, false);
		}

		return (WTDocument) iter;
	}

	/**
	 * 设置eca及eca产生对象的生命周期状态
	 * 
	 * @param ecn
	 * @param reviewObjs
	 * @return
	 * @throws ChangeException2
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static WTArrayList setECAState(WTChangeOrder2 ecn, WTArrayList reviewObjs)
			throws ChangeException2, WTException, WTPropertyVetoException {
		QueryResult ecas = ChangeHelper2.service.getChangeActivities(ecn);
		logger.info("方法是否执行ecas=" + ecas.size());
		while (ecas.hasMoreElements() && ecas != null) {
			WTChangeActivity2 eca = (WTChangeActivity2) ecas.nextElement(); // 获取ECA
			State st = State.toState("RESOLVED"); // 设置所有ECA状态为“已解决（RESOLVED）”
			LifeCycleState lf = new LifeCycleState();
			lf.setState(st);
			eca.setState(lf);
			QueryResult qr = ChangeHelper2.service.getChangeablesAfter(eca); // 获取ECA说产生的WTPart对象
			while (qr.hasMoreElements() && qr != null) {
				Changeable2 changeable = (Changeable2) qr.nextElement();
				if (changeable instanceof WTPart) {
					WTPart wtPart = (WTPart) changeable;
					String statu = wtPart.getLifeCycleState().toString();
					if (("NewProductModify").equals(statu) || ("INWORK").equals(statu)) {
						ext.com.workflow.WorkflowUtil.setLifeCycleState(wtPart, "NewProduct");
					} else if (("MassProductionReleaseModify").equals(statu)) {
						ext.com.workflow.WorkflowUtil.setLifeCycleState(wtPart, "MassProductionRelease");
					} else if (("APPROVE_MODIFICATIONS").equals(statu)) {
						ext.com.workflow.WorkflowUtil.setLifeCycleState(wtPart, "APPROVAL");
					}
					reviewObjs.add(wtPart);
				}
			}
		}
		return reviewObjs;
	}

	/**
	 * 设置更改过的零部件的状态
	 * 
	 * @param list
	 * @throws WTException
	 */
	public static void setFinishedGoodState(WTArrayList list) throws WTException {

		if ((list != null) && (list.size() > 0)) {

			for (int i = 0; i < list.size(); i++) {

				Object object = (Object) list.get(i);
				if ((object != null) && (object instanceof ObjectReference)) {
					ObjectReference obf = (ObjectReference) object;
					object = obf.getObject();
				}

				if ((object != null) && (object instanceof WTPart)) {
					WTPart part = (WTPart) object;
					String statu = part.getLifeCycleState().toString();
					if (("NewProductModify").equals(statu)) {
						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, "NewProduct");
					} else if (("MassProductionReleaseModify").equals(statu)) {
						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, "MassProductionRelease");
					} else if (("APPROVAL").equals(statu)) {
						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, "NewProduct");
					}
				}

			}

		}

	}

	/**
	 * 判断eca产生对象是否符合要求
	 * 
	 * @param ecn
	 * @throws ChangeException2
	 * @throws WTException
	 */
	public static void checkState(WTChangeOrder2 ecn) throws ChangeException2, WTException {
		QueryResult ecas = ChangeHelper2.service.getChangeActivities(ecn);
		StringBuffer logs = new StringBuffer();
		if (ecas != null) {
			while (ecas.hasMoreElements()) {
				WTChangeActivity2 eca = (WTChangeActivity2) ecas.nextElement();
				QueryResult qr = ChangeHelper2.service.getChangeablesAfter(eca);

				while (qr.hasMoreElements()) {
					Changeable2 changeable = (Changeable2) qr.nextElement();

					if (changeable instanceof WTPart) {
						WTPart wtPart = (WTPart) changeable;
						String statu = wtPart.getLifeCycleState().toString();

						// 2013-11-20
						if (!stateList.contains(statu)) {
							String number = wtPart.getNumber();
							String view = wtPart.getViewName();
							logs.append(number);
							logs.append(",");
							logs.append(view);
							logs.append("\n");
						}

					}
				}
			}
		}

		if (logs.length() > 0) {
			logs.append("状态不符合状态要求！");
			throw new WTException(logs.toString());
		}

	}

	/**
	 * 获取PBO下的相关文档
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 */
	public static WTArrayList getPBODocument(WTPart part) throws WTException {
		objectList.clear();
		Object oc = part;
		objectList.add(oc);
		QueryResult qc = PartDocServiceCommand.getAssociatedCADDocuments(part);
		while (qc.hasMoreElements()) {
			logger.info("进入方法体");
			Object object = qc.nextElement();
			objectList.add(object);
		}
		QueryResult qr = PartDocServiceCommand.getAssociatedDescribeDocuments(part);
		while (qr.hasMoreElements()) {
			logger.info("进入方法体！ qr=" + qr);
			Object object = qr.nextElement();
			objectList.add(object);
		}
		QueryResult qa = PartDocServiceCommand.getAssociatedReferenceDocuments(part);
		while (qa.hasMoreElements()) {
			Object object = qa.nextElement();
			objectList.add(object);
		}
		return objectList;
	}

	/**
	 * 遍历集合，根据不同对象设置状态
	 * 
	 * @param list
	 *            要遍历的集合
	 * @param state
	 *            要设置的状态
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 */
	public static void setPartState(WTArrayList plist, String state, String stateOne)
			throws WTPropertyVetoException, WTException {
		logger.info("进入流程后台程序plist=" + plist + ";;;;;;state=" + state + ">>>>>>>>>>>stateOne=" + stateOne);
		for (int i = 0; i < plist.size(); i++) {
			logger.info("进入方法体中。");
			Object object = plist.get(i);
			if (object instanceof ObjectReference) {
				ObjectReference ref = (ObjectReference) object;
				object = ref.getObject();
			}
			if (object instanceof WTPart) {
				WTPart part = (WTPart) object;
				ext.com.workflow.WorkflowUtil.setLifeCycleState(part, state);
			} else if (object instanceof WTDocument) {
				WTDocument wd = (WTDocument) object;
				String softType = ext.com.iba.IBAUtil.getSoftType(wd).getLogicalIdentifier();
				if (softType.contains("Acknowledgment")) {
					ext.com.workflow.WorkflowUtil.setLifeCycleState(wd, stateOne);
				}
			}
		}
	}

	/**
	 * 将ECN中的团队复制到ECA中
	 * 
	 * @param ecn
	 * @throws ChangeException2
	 * @throws WTException
	 */
	public static void copyRolesToBatchObjects(WTChangeOrder2 ecn) throws ChangeException2, WTException {
		logger.info("进入方法体《《《《《《《《《ecn=" + ecn);
		QueryResult qr = ChangeHelper2.service.getChangeActivities(ecn);
		logger.info("获取ecn下的所有eca对象qr=" + qr);
		WTArrayList walist = new WTArrayList();
		while (qr.hasMoreElements() && qr != null) {
			Object object = qr.nextElement();
			walist.add(object);
		}
		logger.info("《《《《《《《《《《《《《walist=" + walist);
		Team processTeam = ext.com.workflow.WorkflowUtil.getTeam((TeamManaged) ecn);
		for (int i = 0; i < walist.size(); i++) {
			Object destObj = walist.getPersistable(i);
			if (destObj instanceof TeamManaged) {
				ext.com.workflow.WorkflowUtil.copyTeam(processTeam, (TeamManaged) destObj);
			}
		}

	}

	/**
	 * 卡版本，小版本必须大于0
	 * 
	 * @param revisionControlled
	 * @throws WTException
	 */
	public static void checkPartIteration(RevisionControlled revisionControlled) throws WTException {
		if (revisionControlled != null) {
			String iteration = revisionControlled.getIterationIdentifier().getValue();
			if (iteration.equals("0")) {
				throw new WTException("小版本不能为0,必须检出检入后才能提交!");
			}
		}

	}

	/**
	 * 检出当前版本的供应商是否与前一版本的供应商相同
	 * 
	 * @param revisionControlled
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void checkPartSupplier(Object pbo) throws RemoteException, WTException {
		if (pbo != null && pbo instanceof WTPart) {
			WTPart part = (WTPart) pbo;
			checkPartSupplier(part);
		}
	}

	/**
	 * 检出当前版本的供应商是否与前一版本的供应商相同
	 * 
	 * @param revisionControlled
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void checkPartSupplier(WTPart part) throws RemoteException, WTException {
		String version = getVersion(part);
		WTPart needPart = CommonPDMUtil.getWTPartByNumViewAndVersion(part.getNumber(), part.getViewName(), version);
		// 当前版本供应商
		String supplier = (String) IBAUtil.getIBAValue(part, "partSupplier");
		// 前一版本供应商
		String supplier1 = (String) IBAUtil.getIBAValue(needPart, "partSupplier");

		// 判断条件添加只有原材料及其子件走二供时需要检出“供应商”是否修改 add kwang 2013-12-02
		if (TMTypeUtil.isRawMaterial(needPart) || TMTypeUtil.isPolarizer(needPart)
				|| TMTypeUtil.isPhantomPolarizer(needPart)) {
			// 判断初始小版本(比如：0.0,1.0,2.0)的供应商是否与流程提交时的供应商相同
			if (supplier != null && supplier.equals(supplier1)) {
				throw new WTException("当前版本的供应商与前一版本的供应商相同流程流程无法继续!");
			} else if (supplier == null) {
				throw new WTException("必须填写供应商!");
			}
		}
	}

	/**
	 * 获取对象的大小版本组成的版本序列值
	 * 
	 * @param revisionControlled
	 * @return
	 */
	public static String getVersion(RevisionControlled revisionControlled) {
		String version = "";
		if (revisionControlled != null) {
			String majorVersion = revisionControlled.getVersionIdentifier().getValue();
			// 获取小版本
			// String minorVersion = revisionControlled.getIterationIdentifier().getValue();
			version = majorVersion + "." + "0";
		}
		return version;
	}

	/**
	 * 根据零部件，获取其大版本号
	 * 
	 * @param part
	 *            想要获取大版本号的零部件
	 * @return 返回该零部件的版本号，如果零部件为空，返回空
	 * @throws WTException
	 *             <br>
	 *             <br>
	 *             <b>Revision History</b> <br>
	 *             <b>Rev:</b> 1.0 - 2006/03/15, Gaoxu <br>
	 *             <b>Comment:</b> Initial release.
	 */
	public static String getPartVersionNumber(WTPart part) throws WTException {
		String version = "";
		try {
			version = VersionControlHelper.getVersionIdentifier((Versioned) part).getValue();
		} catch (VersionControlException e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 根据零部件，获取其小版本号
	 * 
	 * @param part
	 *            想要获取小版本号的零部件
	 * @return 返回该零部件的小版本号，如果零部件为空，返回空
	 * @throws WTException
	 *             <br>
	 *             <br>
	 *             <b>Revision History</b> <br>
	 *             <b>Rev:</b> 1.0 - 2006/03/15, Gaoxu <br>
	 *             <b>Comment:</b> Initial release.
	 */
	public static String getPartReversionNumber(WTPart part) throws WTException {
		String iteration = "";
		try {
			iteration = VersionControlHelper.getIterationIdentifier((Iterated) part).getValue();
		} catch (VersionControlException e) {
			e.printStackTrace();
		}
		return iteration;
	}

	/**
	 * 获取“Desgin”视图对象的其他视图对象并添加到集合中
	 * 
	 * @param wtObject
	 * @return
	 */
	public static WTArrayList getAllPartViews(WTObject wtObject) {
		WTArrayList erpObjList = new WTArrayList();
		WTPart part = null;

		if (wtObject == null) {
			return erpObjList;
		}

		if (wtObject instanceof WTPart) {
			part = (WTPart) wtObject;
		}

		try {

			View[] view = getAllViews();
			if (view != null && view.length > 0) {

				for (int i = 0; i < view.length; i++) {
					View partView = view[i];

					if (partView != null) {
						getAllPartViews(part, erpObjList, partView);
					}
				}
			}

		} catch (ViewException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		return erpObjList;
	}

	/**
	 * 获取“Desgin”视图对象的其他视图对象并添加到集合中
	 * 
	 * @param part
	 * @param erpObjList
	 * @param partView
	 * @throws WTException
	 */
	private static void getAllPartViews(WTPart part, WTArrayList erpObjList, View partView) throws WTException {

		WTPart newPart = getWTPartByMasterAndView((WTPartMaster) part.getMaster(), partView);
		// ERP集成的时候不需要“Deign”
		if ((newPart != null) && (!D_VIEW.equals(newPart.getViewName()))) {// modify by lilin
																			// equals判断，常量最好在前，不然容易出现空指针异常
																			// newPart.getViewName().equals( D_VIEW )
			// if( ( newPart != null ) ){
			if (!erpObjList.contains(newPart)) {
				erpObjList.add(newPart);
			}
		}
	}

	/**
	 * 获取当前系统中所有的视图，返回值为一个数组。这个数组可能存在null
	 * 
	 * @return
	 * @throws ViewException
	 * @throws WTException
	 */
	public static View[] getAllViews() throws ViewException, WTException {

		return ViewHelper.service.getAllViews();
	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByMasterAndView(WTPartMaster master, View view) throws WTException {
		WTPart part = null;

		// 根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(view, null);
		try {
			standardConfig.setView(view);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		// 根据master和视图获取对应最新的视图版本零部件
		QueryResult qr1 = ConfigHelper.service.filteredIterationsOf(master, standardConfig);
		if (qr1.hasMoreElements()) {
			part = (WTPart) qr1.nextElement();
		}
		return part;
	}

	/**
	 * 便利集合获取父件的所有子件并根据父件设置子件状态
	 * 
	 * add kwang 2013-12-03
	 * 
	 * @param part
	 * @return
	 */
	public static void setChangeableFils(WTArrayList reviewObjs) {

		if (reviewObjs != null) {

			for (int i = 0; i < reviewObjs.size(); i++) {
				Object object = reviewObjs.get(i);

				if (object != null && object instanceof ObjectReference) {
					ObjectReference orf = (ObjectReference) object;
					object = orf.getObject();
				}

				if (object != null && object instanceof WTPart) {
					WTPart part = (WTPart) object;
					logger.info("Debug   setPartFils...part:" + part.getNumber());
					State state = part.getLifeCycleState();
					if (state != null) {
						String partState = state.toString();
						logger.info("Debug   setPartFils...partState:" + partState);
						setPartFils(part, partState);
					}
				}
			}
		}
	}

	/**
	 * 获取父件的所有子件并根据父件设置子件状态
	 * 
	 * add kwang 2013-12-03
	 * 
	 * @param part
	 * @return
	 */
	public static void setPartFils(WTPart part, String state) {
		if (part != null) {
			try {
				QueryResult subNodes = WTPartHelper.service.getUsesWTParts(part, WTPartStandardConfigSpec
						.newWTPartStandardConfigSpec(ViewHelper.service.getView(part.getViewName()), null));

				if (subNodes != null) {

					while (subNodes.hasMoreElements()) {
						Persistable[] aSubNodePair = (Persistable[]) subNodes.nextElement();
						WTPart tempPart = null;
						if (aSubNodePair != null && aSubNodePair.length > 0) {

							if (aSubNodePair[1] instanceof WTPartMaster) {
								tempPart = PartUtil.getLatestPartByPartMaster((WTPartMaster) aSubNodePair[1]);
							} else if (aSubNodePair[1] instanceof WTPart) {
								tempPart = (WTPart) aSubNodePair[1];
							}
							logger.info("Debug   setPartFils...tempPart:" + tempPart.getNumber());
							setPartsFilsState(tempPart, state);
						}
						setPartFils(tempPart, state);
					}
				}
			} catch (ViewException e) {
				e.printStackTrace();
			} catch (WTException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 跟父件设置子件状态
	 * 
	 * @param part
	 * @param reviewObjs
	 * @throws WTException
	 */
	private static void setPartsFilsState(WTPart part, String setPartState) throws WTException {
		logger.info("Debug   setPartsFilsState...part:" + part.getNumber() + "   ");
		if (part != null) {
			State state = part.getLifeCycleState();

			if (state != null) {
				String partState = state.toString();

				if (partState != null) {

					if (partState.equals(APPROVE_MODIFICATIONS)) {

						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, APPROVEL);
					} else if (partState.equals(MASS_PRODUCT_MODIFY)) {

						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, MASS_RELEASE);
					} else if (partState.equals(NEW_PRODUCT_MODIFY)) {

						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, NEW_PRODUCT);
					} else if (partState.equals(TRIAL_PRODUCTION_MODIFY)) {

						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, TRIAL_PRODUCTION);
					} else if (partState.equals(CUSTOMER_SAMPLE_MODIFY)) {

						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, CUSTOMER_SAMPLE);

					} else if (partState.equals(RISK_ORDER_MODIFY)) {

						ext.com.workflow.WorkflowUtil.setLifeCycleState(part, RISK_ORDER);
					} else if (partState.equals(INWORK)) {

						if (MASS_RELEASE.equals(setPartState)) {

							ext.com.workflow.WorkflowUtil.setLifeCycleState(part, MASS_RELEASE);
						} else if (NEW_PRODUCT.equals(setPartState)) {

							ext.com.workflow.WorkflowUtil.setLifeCycleState(part, NEW_PRODUCT);
						} else if (TRIAL_PRODUCTION.equals(setPartState)) {

							if (TMTypeUtil.isFinishedGood(part) || TMTypeUtil.isSemiFinishedGood(part)) {
								ext.com.workflow.WorkflowUtil.setLifeCycleState(part, TRIAL_PRODUCTION);
							} else if (TMTypeUtil.isRawMaterial(part)) {
								ext.com.workflow.WorkflowUtil.setLifeCycleState(part, MASS_RELEASE);
							}
						} else if (CUSTOMER_SAMPLE.equals(setPartState)) {

							if (TMTypeUtil.isFinishedGood(part) || TMTypeUtil.isSemiFinishedGood(part)) {
								ext.com.workflow.WorkflowUtil.setLifeCycleState(part, CUSTOMER_SAMPLE);
							} else if (TMTypeUtil.isRawMaterial(part)) {
								ext.com.workflow.WorkflowUtil.setLifeCycleState(part, MASS_RELEASE);
							}
						} else if (RISK_ORDER.equals(setPartState)) {

							if (TMTypeUtil.isFinishedGood(part) || TMTypeUtil.isSemiFinishedGood(part)) {
								ext.com.workflow.WorkflowUtil.setLifeCycleState(part, RISK_ORDER);
							} else if (TMTypeUtil.isRawMaterial(part)) {
								ext.com.workflow.WorkflowUtil.setLifeCycleState(part, MASS_RELEASE);
							}
						}
					}
				}
			}

		}

	}

	/**
	 * 设置产生对象状态 并添加到集合中
	 * 
	 * @param wtObj
	 * @return
	 */
	public static WTArrayList setChangeableState(WTObject wtObj) {
		WTArrayList reviewObjs = new WTArrayList();

		if (wtObj != null && wtObj instanceof WTChangeOrder2) {
			WTChangeOrder2 ecn = (WTChangeOrder2) wtObj;

			try {
				QueryResult queryResultECA = ChangeHelper2.service.getChangeActivities(ecn);

				if (queryResultECA != null) {

					while (queryResultECA.hasMoreElements()) {

						WTChangeActivity2 eca = (WTChangeActivity2) queryResultECA.nextElement(); // 获取ECA

						setChangeableState(eca, reviewObjs);
					}
				}
			} catch (ChangeException2 e) {
				e.printStackTrace();
			} catch (WTException e) {
				e.printStackTrace();
			}
		}
		return reviewObjs;
	}

	/**
	 * 设置产生对象状态 并添加到集合中
	 * 
	 * @param eca
	 * @param reviewObjs
	 * @throws ChangeException2
	 * @throws WTException
	 */
	private static void setChangeableState(WTChangeActivity2 eca, WTArrayList reviewObjs)
			throws ChangeException2, WTException {

		if (eca != null) {
			QueryResult queryResultPart = ChangeHelper2.service.getChangeablesAfter(eca);

			if (queryResultPart != null) {

				while (queryResultPart.hasMoreElements()) {

					Changeable2 changeable = (Changeable2) queryResultPart.nextElement();

					if (changeable != null && changeable instanceof WTPart) {
						WTPart part = (WTPart) changeable;
						setPartsState(part, reviewObjs);
					} else if (changeable != null && changeable instanceof WTDocument) {
						WTDocument doc = (WTDocument) changeable;
						setDocsState(doc, reviewObjs);
					} else if (changeable != null && changeable instanceof EPMDocument) {
						EPMDocument epmDoc = (EPMDocument) changeable;
						setEPMDocsState(epmDoc, reviewObjs);
					}
				}
			}
		}
	}

	/**
	 * 设置产生对象中EPM文档类型的状态
	 * 
	 * @param epmDoc
	 * @param reviewObjs
	 * @throws WTException
	 */
	private static void setEPMDocsState(EPMDocument epmDoc, WTArrayList reviewObjs) throws WTException {

		if (epmDoc != null) {
			State state = epmDoc.getLifeCycleState();

			if (state != null) {
				String epmState = state.toString();

				if (epmState != null) {

					if (epmState.equals(APPROVE_MODIFICATIONS)) {

						epmDoc = (EPMDocument) ext.com.workflow.WorkflowUtil.setLifeCycleState(epmDoc, APPROVEL);
					} else if (epmState.equals(MASS_PRODUCT_MODIFY)) {

						epmDoc = (EPMDocument) ext.com.workflow.WorkflowUtil.setLifeCycleState(epmDoc, MASS_RELEASE);
					} else if (epmState.equals(NEW_PRODUCT_MODIFY) || epmState.equals(INWORK)) {

						epmDoc = (EPMDocument) ext.com.workflow.WorkflowUtil.setLifeCycleState(epmDoc, NEW_PRODUCT);
					}

					reviewObjs.add(epmDoc);
				}
			}
		}
	}

	/**
	 * 设置产生对象中文档类型的状态
	 * 
	 * @param doc
	 * @param reviewObjs
	 */
	private static void setDocsState(WTDocument doc, WTArrayList reviewObjs) {

		if (doc == null) {
			return;
		}

		if (!State.INWORK.equals(doc.getLifeCycleState())) {
			return;
		}

		try {
			doc = (WTDocument) ext.com.workflow.WorkflowUtil.setLifeCycleState(doc, RELEASED);
		} catch (WTException e) {
			e.printStackTrace();
		}

		reviewObjs.add(doc);
	}

	/**
	 * 设置产生对象状态 并添加到集合中
	 * 
	 * @param part
	 * @param reviewObjs
	 * @throws WTException
	 */
	private static void setPartsState(WTPart part, WTArrayList reviewObjs) throws WTException {

		if (part != null) {
			State state = part.getLifeCycleState();

			if (state != null) {
				String partState = state.toString();

				if (partState != null) {

					if (partState.equals(APPROVE_MODIFICATIONS)) {

						part = (WTPart) ext.com.workflow.WorkflowUtil.setLifeCycleState(part, APPROVEL);
					} else if (partState.equals(MASS_PRODUCT_MODIFY)) {

						part = (WTPart) ext.com.workflow.WorkflowUtil.setLifeCycleState(part, MASS_RELEASE);
					} else if (partState.equals(NEW_PRODUCT_MODIFY) || partState.equals(INWORK)) {

						part = (WTPart) ext.com.workflow.WorkflowUtil.setLifeCycleState(part, NEW_PRODUCT);
					} else if (partState.equals(TRIAL_PRODUCTION_MODIFY)) {

						part = (WTPart) ext.com.workflow.WorkflowUtil.setLifeCycleState(part, TRIAL_PRODUCTION);
					} else if (partState.equals(CUSTOMER_SAMPLE_MODIFY)) {

						part = (WTPart) ext.com.workflow.WorkflowUtil.setLifeCycleState(part, CUSTOMER_SAMPLE);
					} else if (partState.equals(RISK_ORDER_MODIFY)) {

						part = (WTPart) ext.com.workflow.WorkflowUtil.setLifeCycleState(part, RISK_ORDER);

					}

					reviewObjs.add(part);
				}
			}
		}
	}

	/**
	 * 设置原材料属性
	 * 
	 * 是否已经样品承认
	 * 
	 * @param wtObject
	 */
	public static void setPartWhetherPartRecognize(WTObject wtObject) {

		if (wtObject == null) {
			return;
		}

		if (wtObject instanceof WTPart) {
			WTPart part = (WTPart) wtObject;

			if (part != null) {
				Hashtable table = new Hashtable();
				table.put(WHETHER_PART_RECOGNIZE, "是");
				try {
					IBAUtil.setSoftTypeIBAValues(part, table);

					part = (WTPart) CoreUtil.checkoutObject(part);
					CoreUtil.checkinObject(part, "同步“是否已经样品承认”属性");

				} catch (WTException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void updatePartSupplier(WTObject wtObject) {
		if ((wtObject == null) || (!(wtObject instanceof WTPart))) {
			return;
		}

		WTPart part = (WTPart) wtObject;

		if ((TMTypeUtil.isRawMaterial(part)) || (TMTypeUtil.isCF(part))) {
			boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
			try {
				IBAUtil.forceSetIBAValue(part, "partSupplierWithSystemName", "");
			} catch (WTException e) {
				e.printStackTrace();
			} finally {
				SessionServerHelper.manager.setAccessEnforced(flag);
			}
		}
	}

	/**
	 * 获取所有视图部件add by lilin
	 * 
	 * @param wtObject
	 * @return
	 */
	public static WTArrayList getAllViewParts(WTObject wtObject) {
		WTArrayList objList = new WTArrayList();
		WTPart part = null;
		if (wtObject == null) {
			return objList;
		}
		if (wtObject instanceof WTPart) {
			part = (WTPart) wtObject;
		}
		try {

			View[] view = getAllViews();
			if (view != null && view.length > 0) {
				for (int i = 0; i < view.length; i++) {
					View partView = view[i];
					if (partView != null) {
						WTPart newPart = getWTPartByMasterAndView((WTPartMaster) part.getMaster(), partView);
						if (newPart != null) {
							if (!objList.contains(newPart)) {
								objList.add(newPart);
							}
						}
					}
				}
			}
		} catch (ViewException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		return objList;
	}

}